<template>
  <el-card shadow="never" class="mb10">
    <el-row>
      <el-form ref="formQueryRef" :inline="true" :model="queryData">
        <el-form-item label="标签条编码" prop="labelCode">
          <el-input
            placeholder="请输入标签条编码"
            clearable
            v-model="queryData.labelCode"
          />
        </el-form-item>
        <el-form-item label="标签条名称" prop="labelName">
          <el-input
            placeholder="请输入标签条名称"
            clearable
            v-model="queryData.labelName"
          />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select
            class="my-select"
            clearable
            v-model="queryData.status"
            placeholder="请选择状态"
            @change="initData"
          >
            <el-option label="待核销" value="0"> </el-option>
            <el-option label="已核销" value="1"> </el-option>
            <el-option label="已报废" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间" prop="createTime">
          <el-date-picker
            v-model="queryData.createTime"
            type="datetimerange"
            clearable
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
      </el-form>
      <div class="flex-right">
        <el-button type="primary" :icon="RefreshLeft" @click="resetForm">
          重置
        </el-button>
        <el-button
          type="primary"
          :icon="Search"
          @click="initData"
          class="ml20"
          v-enter="initData"
        >
          搜索
        </el-button>
      </div>
    </el-row>
  </el-card>
  <el-card shadow="never">
    <div class="mb10">
      <el-button type="primary" @click="onDialogStaff()">+新增</el-button>
      <el-button type="success" @click="onPrintEdit">打印</el-button>
      <el-button type="warning" @click="onPrintEdit">打印模板</el-button>
      <el-button @click="dialogLogRef.openDialog()">打印记录</el-button>
    </div>
    <el-table
      stripe
      border
      ref="tableRef"
      v-loading="loading"
      :data="tableData"
      key="id"
      @select="handleSelectionChange"
      @select-all="selectAll"
    >
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column
        v-for="item in options"
        :key="item.type"
        :prop="item.props"
        :type="item.type"
        :label="item.label"
        :width="item.width"
        :align="item.align"
        show-overflow-tooltip
        :fixed="item.fixed"
      >
        <template v-slot:default="{ row }" v-if="item.props === 'createTime'">
          {{ dayjs(row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
        <template v-slot:default="{ row }" v-if="item.props === 'status'">
          <el-text :type="statusTypes[row.status].type">
            {{ row.status_desc || statusTypes[row.status].name }}
          </el-text>
        </template>
        <template v-slot:default="{ row }" v-if="item.props === 'actions'">
          <el-button
            type="primary"
            size="small"
            text
            :disabled="row.status === 1"
            @click="dialogLabelEditRef.openDialog(row)"
          >
            编辑
          </el-button>
          <el-button type="success" size="small" text @click="onPrintEdit(row)">
            打印
          </el-button>
          <el-button
            type="danger"
            size="small"
            text
            :disabled="row.status !== 0"
            @click="onScrap(row)"
          >
            报废
          </el-button>
          <el-button
            type="warning"
            size="small"
            text
            @click="onDialogCancel(row)"
          >
            核销
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      class="mt-4"
      :total="total"
      :page-size="queryData.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </el-card>

  <DialogLabel
    ref="dialogLabelRef"
    @success="handleCurrentChange(1)"
  ></DialogLabel>

  <DialogPrint ref="dialogPrintRef" :ids="printArr"></DialogPrint>

  <DialogLabelEdit
    ref="dialogLabelEditRef"
    @success="handleCurrentChange(1)"
  ></DialogLabelEdit>

  <DialogLog ref="dialogLogRef"></DialogLog>

  <DialogCancel
    ref="dialogCancelRef"
    @success="handleCurrentChange(1)"
  ></DialogCancel>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, RefreshLeft } from "@element-plus/icons-vue";
import { dayjs } from "element-plus";
import api from "@/api/label.js";
import { options } from "./options.js";
import DialogLabel from "./components/dialogLabel.vue";
import DialogLabelEdit from "./components/dialogLabelEdit.vue";
import DialogPrint from "./components/dialogPrint.vue";
import DialogLog from "./components/dialogLog.vue";
import DialogCancel from "./components/dialogCancel.vue";

const router = useRouter();
const queryData = ref({
  pageNo: 1,
  pageSize: 10,
});
const statusTypes = {
  0: { name: "待核销", type: "primary" },
  1: { name: "已核销", type: "success" },
  2: { name: "已报废", type: "danger" },
};
const dialogLabelRef = ref();
const dialogPrintRef = ref();
const dialogLabelEditRef = ref();
const dialogLogRef = ref();
const dialogCancelRef = ref();
const formQueryRef = ref();
const loading = ref(false);
const tableData = ref([]);
const selectList = ref([]);
const printArr = ref([]);
const tableRef = ref();
const total = ref(0);

const selectAll = (arr) => {
  // 是否全选
  if (arr.length !== 0) {
    // 全选
    arr.forEach((item) => {
      const bool = selectList.value.some((ele) => ele.id === item.id); // 存在返回true 否则返回false
      if (!bool) {
        // 不存在添加
        selectList.value.push(item);
      }
    });
  } else {
    // 取消全选
    tableData.value.forEach((item) => {
      selectList.value = selectList.value.filter((ele) => ele.id !== item.id);
    });
  }
};
const handleSelectionChange = (arr, row) => {
  console.log(selectList.value, row);
  // 选择
  const bool = selectList.value.some((ele) => ele.id === row.id); // 存在返回true 否则返回false
  if (bool) {
    // 存在删除
    selectList.value = selectList.value.filter((ele) => ele.id !== row.id);
  } else {
    // 添加
    selectList.value.push(row);
  }
};
const echoSelected = () => {
  setTimeout(() => {
    // 回显选中
    if (selectList.value.length > 0) {
      tableData.value.forEach((item) => {
        if (selectList.value.some((ele) => ele.id === item.id)) {
          tableRef.value.toggleRowSelection(item);
        }
      });
    }
  }, 500);
};
const initData = async () => {
  loading.value = true;
  try {
    const res = await api.page({
      ...queryData.value,
      createTime: queryData.value.createTime?.length
        ? JSON.stringify(queryData.value.createTime)
        : undefined,
    });
    tableData.value = res.data.list;
    total.value = res.data.total;
    selectList.value = [];
    // echoSelected();
  } finally {
    loading.value = false;
  }
};
const selectable = (row) => row.status === 0;

const handleCurrentChange = (val) => {
  queryData.value.pageNo = val;
  initData(queryData.value);
};
const handleSizeChange = (val) => {
  queryData.value.pageSize = val;
  initData(queryData.value);
};

const onDialogStaff = (row = null) => {
  // dialogLabelRef.value.openDialog(row);
  router.push({
    path: "/printLabel",
  });
};
const resetForm = () => {
  formQueryRef.value.resetFields();
};

const onPrintEdit = (row = null) => {
  let labelCodes = [];
  let ids = [];
  if (row?.labelCode) {
    labelCodes = [row.labelCode];
    ids = [row.id];
  } else {
    labelCodes = selectList.value?.map((ele) => ele.labelCode);
    ids = selectList.value?.map((ele) => ele.id);
  }
  if (labelCodes.length || ids.length) {
    router.push({
      path: "/printLabel",
      query: {
        labelCodes: JSON.stringify(labelCodes),
        ids: JSON.stringify(ids),
      },
    });
  } else {
    ElMessage.error(`请选择需要打印的标签条！`);
  }
};

const onPrint = async (row = null) => {
  let arr = [];
  if (row?.id) {
    arr = [row.id];
  } else {
    arr = selectList.value?.map((ele) => ele.id);
  }
  if (arr.length) {
    printArr.value = arr;
    dialogPrintRef.value.openDialog(arr);
  } else {
    ElMessage.error(`请选择需要打印的标签条！`);
  }
};

const onScrap = (row) => {
  ElMessageBox.confirm(
    `确认是否<span style='color:red;'>${
      row.status === 0 ? "报废" : "启用"
    }</span>编号<span style='color:red;'>${row.labelCode}</span>标签条`,
    `${row.status === 0 ? "报废" : "启用"}提示`,
    {
      type: "warning",
      dangerouslyUseHTMLString: true,
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }
  )
    .then(async () => {
      // 状态, 1-核销， 2-报废
      const res = await api.status({
        id: row.id,
        status: 2,
      });
      if (res.data) {
        ElMessage.success(
          res.msg || `${row.status === 0 ? "报废" : "启用"}成功！`
        );
        handleCurrentChange(1);
      } else {
        ElMessage.error(
          res.msg || `${row.status === 0 ? "报废" : "启用"}失败！`
        );
      }
    })
    .catch(() => {});
};

const onDialogCancel = (row) => {
  dialogCancelRef.value.openDialog(row);
};

onMounted(() => {
  initData();
});
</script>
